# views.py

import pdb

from django.shortcuts import render_to_response
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.models import User
from django.template import RequestContext

from psd.register.models import Person, RegRecord, BreakRecord, DateRecord, Event, MatchRecord, LOCATIONS, updateMatchRecords


@staff_member_required
def check_in(request, event_name ):
    
    try:
        event = Event.objects.get(event=event_name)
    except Event.DoesNotExist:
        return render_to_response( 'error.html', {'message' : "Sorry.  You are trying to do check-in for an event that does not exist or is closed.  Please try again." }, 
                                   context_instance=RequestContext(request)  )

    to_update = []
    to_warn = []
    if request.method == 'POST':
        here_list = request.POST.getlist('here')
        RegRecord.objects.filter(event=event_name, id__in=here_list).update(here=True)

        cancel_list = request.POST.getlist('cancelled')
        RegRecord.objects.filter(id__in=cancel_list).update(cancelled=True)

        id_list = request.POST.getlist('paid')
        for x in id_list:
            if x in here_list or x in cancel_list:
                to_update.append(x)
            else:
                to_warn.append(x)
        RegRecord.objects.filter(id__in=to_update).update(paid=True)

    regs = RegRecord.objects.filter( event=event_name ).order_by('nickname')
    viewable = regs.filter(here__exact=False, cancelled__exact=False)
    warnable = regs.filter(id__in=to_warn)
    return render_to_response('checkin.html', {'regs': viewable, 'warnings': warnable})







@staff_member_required
def list_comments(request, event_name, acts):
    """List all comments, notes and referrals made by people registering for specified event.
     Useful for generating who knows whom."""

    regs = RegRecord.objects.filter(event=event_name, cancelled=False).order_by( '-id' )

    return render_to_response('list_comments.html', {'regs': regs, 'event_name':event_name, 'actions':acts})




@staff_member_required
def list_people(request, event_name, acts):
    """List all people and comments made by people registering for specified event"""

    regs = RegRecord.objects.filter(event=event_name, cancelled=False).order_by( '-id' )

    return render_to_response('list_people.html', {'regs': regs, 'event_name':event_name, 'actions':acts})





@staff_member_required
def generateEmailList(request, event_name, acts):
    """Generate mailing list for the event"""

    regs = RegRecord.objects.filter(event=event_name)

    return render_to_response('email_list.html', {'regs': regs, 'event_name':event_name, 'actions':acts})




#@staff_member_required
#def clean_database(request):
def clean_database():
    """Delete person records with no regrecords.  
    Then delete users with no regrecords that are not staff level"""
    
    users = User.objects.all()
    rrs = RegRecord.objects.all()
    
    all_rr_ids= set()
    allfolk = set()
    for rr in rrs:
        folk = [p.psdid for p in rr.people.all() ]
        allfolk.update(folk)
        all_rr_ids.add( rr.psdid )
        
    people_deleted = 0
    for p in Person.objects.all():
        if not p.psdid in allfolk:
            p.delete()
            people_deleted += 1
            
    users_deleted = 0
    for usr in users:
        if not usr.is_staff:
            if not usr.username in all_rr_ids:
                usr.delete()
                users_deleted += 1 
        else:
            print "Skipping staff " + str(usr)
         
    return "database cleaned"
 
#    return render_to_response('clean_database.html', locals())


def fix_group_codes():
    res = ""
    for rr in RegRecord.objects.all():
        if (rr.is_group and len( rr.people.all() ) == 1) or (not rr.is_group and len(rr.people.all()) != 1):
            res += "\n<br>%s  %s  %s  %s" % ( rr.psdid, rr.event, rr.is_group, len(rr.people.all()))
            if rr.is_group:
                 rr.is_group = False
            else:
                 rr.is_group = True
            rr.save()
    return res


class MyAction:
      action = "default"
      action_description = "default action"

      def __init__(self, arg1, arg2):
          self.action=arg1
          self.action_description=arg2
      
ACTIONS = ( MyAction('main', 'Clean Display'),
        MyAction('listcomments', 'List Comments, Notes and Referrals'),
        MyAction('listpeople', 'List People Registered'),
        MyAction('clean', 'Clean Database' ),
        MyAction('fix', 'Fix Group Codes'),
        MyAction('matrix', 'Make the dating matrix files' ),
        MyAction('email', 'Make email list of participants (Only checked folks')
        )

@staff_member_required
def event_manager( request, event_name, action ):

    if action=="" or action=="main":
       results="Click on action desired"
    elif action=="listcomments":
       return list_comments(request,event_name,ACTIONS)
    elif action=="listpeople":
        return list_people(request, event_name,ACTIONS)
    elif action=="clean":
       results=clean_database()
    elif action=="fix":
       results=fix_group_codes()
    elif action=="matrix":
        (cntr,tot) = updateMatchRecords(event_name)
        results = "%s non-zero match records from %s regrecords created" % (cntr, tot )
    elif action=="email":
        results = generateEmailList(request,event_name,ACTIONS)
        return results
    else:
       results="Action '%s' not understood." % (action,)

    return render_to_response( 'event_manager.html', {'event_name':event_name,
                                   'actions':ACTIONS,
                                   'results':results } )
    



@staff_member_required
def potential_matches( request, event_name, psdid ):
    recs = MatchRecord.objects.filter( psdid1=psdid )

    try:
        peep = RegRecord.objects.get( event=event_name, psdid=psdid )
    except:
         return HttpResponseNotFound('<h1>event %s or psdid  %s not real?</h1>' % (event_name, psdid, ) )
 
    for r in recs:
        try:
            r.person2 = RegRecord.objects.get( event=event_name, psdid=r.psdid2 )
        except:
          return HttpResponseNotFound('<h1>psdid %s for %s not found in reg records?</h1>' % (r.psdid2, event_name) )
           
    
    return render_to_response( 'potential_matches.html', locals(),
                                 context_instance=RequestContext(request)  )
    
 
 
@staff_member_required
def break_matches(request, event_name, psdid ):
    
    try:
        event = Event.objects.get(event=event_name)
    except Event.DoesNotExist:
        return render_to_response( 'error.html', {'message' : "Sorry.  You are trying to do match list for an event '%s' that does not exist or is closed.  Please try again." % (event_name,)}, 
                                   context_instance=RequestContext(request)  )

    try:
        rr = RegRecord.objects.get(psdid=psdid, event=event_name)
    except Event.DoesNotExist:
        return render_to_response( 'error.html', {'message' : "Sorry.  You are trying to do match list for a PSDID '%s' that does not exist or is closed.  Please try again." % (psdid,) }, 
                                   context_instance=RequestContext(request)  )

    break_list = []
    if request.method == 'POST':
        break_list = request.POST.getlist('break')
        brecs = MatchRecord.objects.filter(event=event_name, psdid1=psdid, psdid2__in=break_list)
        for br in brecs:
            mt = BreakRecord(psdid=psdid, other_psdid=br.psdid2, notes="hand break")
            mt.save()
            br.delete()

    matches = MatchRecord.objects.filter( event=event_name, psdid1=psdid ).order_by('psdid2')
    for m in matches:
        p2 = RegRecord.objects.get( psdid=m.psdid2, event=event_name )
        m.namestring = p2.namestring
        
    return render_to_response('matchlist.html', {'matches': matches, 'rr': rr, 'breaklist':break_list})



 
@staff_member_required
def date_sheet(request, event_name, psdid ):
    
    try:
        event = Event.objects.get(event=event_name)
    except Event.DoesNotExist:
        return render_to_response( 'error.html', {'message' : "Sorry.  You are trying to do date list for an event '%s' that does not exist or is closed.  Please try again." % (event_name,)}, 
                                   context_instance=RequestContext(request)  )

    try:
        rr = RegRecord.objects.get(psdid=psdid, event=event_name)
    except Event.DoesNotExist:
        return render_to_response( 'error.html', {'message' : "Sorry.  You are trying to do date list for a PSDID '%s' that does not exist or is closed.  Please try again." % (psdid,) }, 
                                   context_instance=RequestContext(request)  )

    if request.method == 'POST':
        break_list = request.POST.getlist('break')
        brecs = MatchRecord.objects.filter(event=event_name, psdid1=psdid, psdid2__in=break_list)
        for br in brecs:
            mt = BreakRecord(psdid=psdid, other_psdid=br.psdid2, notes="hand break")
            mt.save()
            br.delete()

    dates = DateRecord.objects.filter( event=event_name, psdid=psdid ).order_by('round')
    
    return render_to_response('datesheet.html', {'dates': dates, 'rr': rr, 'event':event } )

    
